<template>
  <div ref="refDashboard" class="dashboard">
    <div class="btn-box">
      <el-button v-hasPerm="strPerm" type="primary" @click="showMsgBox">MessageBox</el-button>
      <el-button v-hasPerm="strPerm" type="primary" @click="showDig">弹窗表格</el-button>
      <el-button link type="info" @click="showMsg('info')">info</el-button>
      <el-button link type="success" @click="showMsg('success')">success</el-button>
      <el-button link type="warning" @click="showMsg('warning')">warning</el-button>
      <el-button link type="danger" @click="showMsg('error')">error</el-button>
    </div>
    <div style="margin-top: 20px">
      <span style="color:#e7434f">窗口尺寸：</span><span>{{ windowWidth }} x {{ windowHeight }}</span>
    </div>
    <div class="token">
      <span style="color:#e7434f">token：</span>{{ userStore.accessToken }}
    </div>
    <div class="icon-box">
      <span style="color:#e7434f;line-height: 30px">图标：</span>
      <el-icon color="#67c23a" size="20">
        <component :is="$icon('TrophyBase')"/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <component :is="$icon('Setting')"/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <component :is="$icon('Menu')"/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <component :is="$icon('User')"/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <i-ep-arrow-right/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <i-ep-house/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <i-ep-circle-check-filled/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <i-ep-avatar/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <i-ep-help-filled/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <i-ep-tools/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <icon-dark/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <icon-light/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <icon-info/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <icon-success/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <icon-warning/>
      </el-icon>
      <el-icon color="#67c23a" size="20">
        <icon-error/>
      </el-icon>
    </div>
    <div class="form-box">
      <div class="form-box-item">
        <el-form :model="formData" label-suffix=":" label-width="100px">
          <el-form-item label="用户ID" prop="userId">
            <el-input v-model="formData.userId" placeholder="请输入用户ID"/>
          </el-form-item>
          <el-form-item label="用户名" prop="userName">
            <el-input v-model="formData.userName" placeholder="请输入用户名"/>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="formData.role" clearable placeholder="请选择用户角色">
              <el-option v-for="item in roles"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="生日" prop="birthday">
            <el-date-picker v-model="formData.birthday" placeholder="请选择生日" @change="dateChange">
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div class="btn-box">
          <el-button :icon="$icon('TrophyBase')" @click="Emessage('success', `提交成功。`)">
            提交
          </el-button>
          <el-button :icon="$icon('Remove')">重置</el-button>
          <el-button>
            <template #icon>
              <icon-error></icon-error>
            </template>
            自定义svg图标
          </el-button>
          <el-button type="danger" @click="exportExcel">导出</el-button>
        </div>
      </div>
      <div class="color-select">
        <template v-if="eyeDropperIsSupported">
          <div>颜色拾取支持: {{ eyeDropperIsSupported }}</div>
          <div>颜色代码(点击复制): <span :style="{ color: sRGBHex }" style="cursor: pointer" @click="copyTxt(sRGBHex)">{{
              sRGBHex
                                                                                                                       }}</span></div>
          <el-button :disabled="!eyeDropperIsSupported" type="success" @click="() => open()">颜色拾取</el-button>
        </template>
        <div v-else>
          <span>您的浏览器不支持！</span>
        </div>
      </div>
      <div class="leafer-dom" id="leaferDom"></div>
    </div>
    <div class="pag-box">
      <PAGAnimationView/>
    </div>

    <el-dialog
        v-model="dialogVisible"
        :close-on-click-modal="false"
        :show-close="false"
        append-to="body"
        class="table-dialog"
        draggable
        width="1200"
    >
      <template #header>
        <div class="title">
          <span style="margin-right: 20px;">我是标题</span>
        </div>
        <i class="ali-error" :style="{color:appStore.theme==='dark'?'#084957':'#031E5D'}"
           @click="dialogVisible = false"></i>
      </template>
      <ws-table
          :columns="tableColumns"
          :url="url"
          layout="total, prev, pager, next">
        <template #unit="{row}">
          {{ row.unit.unitName }}
        </template>
        <template #content="{row}">
          {{ row.userContent.content.fastCodeName }}
        </template>
        <template #vehicleNo="{row}">
          {{ row.userContent.vehicleNo }}
        </template>
        <template #level="{row}">
            <span style="color:deepskyblue">
              {{ row.level }}
            </span>
        </template>
      </ws-table>
    </el-dialog>
    <div :style="style" class="drag-box">
      <div ref="refDragBox" class="title">
        可拖拽移动
      </div>
      <div class="drag-content">
        <el-checkbox v-model="isDrag">允许拖动[{{ Math.round(dragX) }}, {{ Math.round(dragY) }}]</el-checkbox>
        <div class="content-canvas">
          <div class="item1">
            <css-doodle>
              @grid: 1 / 60% auto;
              background: radial-gradient(
              pink, yellow, red, red
              );
              mask: @svg-polygon(
              split: 400;
              scale: .7;
              r: cos(7t)^4 + sin(7t) +.3;
              );
            </css-doodle>
          </div>
          <div class="item2">
          </div>
          <div class="item3">
          </div>
          <div class="item4">
            <LeaferApp :width="240" :height="145">
              <Leafer type="draw" @tap="changeColor">
                <template
                    v-for="row in 34"
                    :key="row"
                >
                  <Star
                      v-for="col in 16"
                      :key="col"
                      around="center"
                      corners="6"
                      :rotation="rotation"
                      :x="(row - 1) * 20" :y="(col-1) * 20"
                      :width="20" :height="20"
                      :fill="fill"
                      :draggable="true"
                  />
                </template>
              </Leafer>
            </LeaferApp>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {dayjs} from 'element-plus'
import setting from '../../../../mock/setting.js'
import {useAppStore} from '@/store/index.js'
import {Leafer, Path, Platform, Rect} from 'leafer-ui'
import {flower, snake} from '@/utils/svgPath.js'
import {LeaferApp} from 'leafer-vue'
import 'css-doodle'

defineOptions({
  name: 'libView_comExample'
})

const appStore = useAppStore()
const userStore = useUserStore()
const refDashboard = ref()
const refDragBox = ref()
const state = reactive({
  isDrag: true,
  url: setting.isMockData ? 'post|/user/page' : 'post|/basicParameter/maintainer/listAll',
  dialogVisible: false,
  formData: {
    userId: userStore.userId,
    userName: userStore.userName,
    role: '',
    birthday: ''
  },
  roles: [
    {
      value: 'admin',
      label: '管理员'
    },
    {
      value: 'user',
      label: '用户'
    }
  ],
  tableColumns: []
})
const {isDrag, url, dialogVisible, formData, roles, tableColumns} = toRefs(state)

onMounted(() => {
  if (setting.isMockData) {
    state.tableColumns = [
      {label: '页码', prop: 'page', align: 'center', width: 60},
      {label: '姓名', prop: 'staffName', width: 100},
      {label: '手机号', prop: 'phone'},
      {label: '地址', prop: 'address'},
      {label: 'Email', prop: 'email'},
      {label: '创建时间', prop: 'createTime'},
      {label: '会员等级', type: 'slot', prop: 'level'}
    ]
  } else {
    state.tableColumns = [
      {label: '人员编号', prop: 'userId', minWidth: 130},
      {label: '人员名称', prop: 'userName', minWidth: 130},
      {label: '维护单位', type: 'slot', prop: 'unit', minWidth: 180},
      {label: '电话号码', prop: 'telephone', minWidth: 105},
      {
        label: '人员职责', type: 'slot', prop: 'content', minWidth: 105,
        filters: [{text: '管理人员', value: '管理人员'}, {text: '维护人员', value: '维护人员'}],
        filterMethod: (value, row, column) => {
          const prop = column['property']
          return row['userContent'][prop]['fastCodeName'] === value
        }
      },
      {label: '车牌号码', type: 'slot', prop: 'vehicleNo', minWidth: 105},
      {label: '小组成员', prop: 'userGroupNames', minWidth: 105},
      {label: '维护片区', prop: 'areaNames', minWidth: 105},
      {label: '用户描述', prop: 'userDesc', minWidth: 170}
    ]
  }
  const leafer = new Leafer({
    view: 'leaferDom' // 支持 window 、div、canvas 标签对象， 可使用id字符串(不用加 # 号)
    // fill:'#123'
  })
  const rectFlower = new Rect({
    width: 150,
    height: 150,
    fill: {
      type: 'image',
      url: Platform.toURL(flower, 'svg'),
      mode: 'stretch'
    },
    draggable: true
  })
  leafer.add(rectFlower)
  const rectSnake = new Rect({
    x: 150,
    width: 150,
    height: 150,
    fill: {
      type: 'image',
      url: Platform.toURL(snake, 'svg'),
      mode: 'stretch'
    },
    draggable: true
  })
  leafer.add(rectSnake)
})

const rotation = ref(0)

function animate() {
  rotation.value += 2
  requestAnimationFrame(animate)
}

animate()
const fill = ref('#409EFF')

function changeColor() {
  fill.value = `#${Math.floor(Math.random() * 0xFFFFFF).toString(16)}`
}

const showMsg = (type) => {
  Emessage(type, `${type}:消息内容。`)
}
const showDig = () => {
  state.dialogVisible = true
}
const showMsgBox = () => {
  EmessageBox('确认删除吗？', '提示').then(() => {
    Emessage('success', `删除成功。`)
  }).catch(() => {
    Emessage('warning', `取消操作。`)
  })
}
const dateChange = () => {
  console.log(dayjs(state.formData.birthday).format('YYYY-MM-DD'))
}
// 权限命令字
const strPerm = computed(() => {
  /*if (setting.isMockData) {
   return 'zwswood'
   } else {
   return '/tmms/basicParameter/maintainer/list'
   }*/
  return 'zwswood'
})
const disabled = computed(() => !state.isDrag)
const {x: dragX, y: dragY, style} = useDraggable(refDragBox, {
  containerElement: refDashboard, // 允许拖动的容器
  initialValue: {x: 500, y: 300},
  preventDefault: true,
  disabled
})


const {width: windowWidth, height: windowHeight} = useWindowSize()

const {isSupported: eyeDropperIsSupported, open, sRGBHex} = useEyeDropper()
const {text, isSupported: clipboardIsSupported, copy} = useClipboard()
const copyTxt = (rgb) => {
  if (clipboardIsSupported) {
    copy(rgb)
    Emessage('success', '复制成功！')
  } else {
    Emessage('error', '您的浏览器不支持！')
  }
}
const exportExcel = () => {
  request({
    url: '/deployDevice/report/export',
    method: 'get',
    params: {
      acquisDeviceId: 100
    }
  }).then(res => {
    if (res.code === 200) {
      if (!res.data['excel']) {
        Emessage('warning', '无任何数据导出，请确认内容。')
        console.log('sdf')
        return false
      }
      try {
        const blob = new Blob([stringToArrayBuffer(res.data['excel'])])
        const elink = document.createElement('a')
        elink.download = 'deployDevice.xlsx'
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } catch (e) {
        Emessage('error', e)
      }
    } else {
      Emessage('error', res.data.error || res.message)
    }
  })
}

const headerBg = computed(() => {
  console.log('dialog的header')
  return appStore.theme === 'dark' ? 'linear-gradient(87deg, #0b5565 1%, #1de5e6 51%)' : 'linear-gradient(87deg, #2165cc 1%, #dde9f9 51%)'
})
const tableBg = computed(() => tableStyle[appStore.theme].tableBg)
const cellBg = computed(() => tableStyle[appStore.theme].cellBg)
</script>
<style lang="scss" scoped>
.dashboard {
  height: 100%;
  width: 100%;
  position: relative;
  --dialog-header-bg: v-bind(headerBg);
  --table-bg: v-bind(tableBg);
  --cell-bg: v-bind(cellBg);

  .btn-box {
    display: flex;
  }

  .token {
    margin-top: 20px;
    color: #67c23a;
    width: 100%;
    word-wrap: break-word;
    line-height: 20px;
  }

  .icon-box {
    display: flex;
    margin-top: 20px;

    i {
      margin: 5px
    }
  }

  .form-box {
    display: flex;

    .form-box-item {
      width: 400px;

      :deep(.el-input) {
        width: 300px;
      }

      .btn-box {
        display: flex;
        justify-content: flex-end;
      }
    }

    .color-select {
      margin-left: 20px;
      line-height: 24px;
    }

    .leafer-dom {
      width: 400px;
      height: 300px;
    }
  }

  :deep(.el-dialog.table-dialog) {
    background: var(--table-bg);
    padding: 0;

    .el-dialog__header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      height: 32px;
      background: var(--dialog-header-bg);
      padding: 0;
      color: #60FCFF;

      .title {
        margin-left: 20px;
      }

      i {
        margin-right: 20px;
        font-size: 20px;
        cursor: pointer;
      }
    }

    .el-dialog__body {
      padding: 20px;
      height: 505px;

      .el-table {
        .el-table__inner-wrapper:before {
          background: transparent;
        }

        .el-table__header {
          .cell {
            //background: #1B5B68;
          }
        }

        .el-table__body {
          .cell {
            line-height: 30px;
            background: var(--cell-bg);
            width: auto !important;
          }
        }
      }
    }
  }

  .drag-box {
    position: absolute;
    z-index: 1;
    display: flex;
    flex-direction: column;
    width: 500px;
    color: #fff;
    border-radius: 4px;
    background: #0c6688;

    .title {
      height: 32px;
      line-height: 32px;
      background: #409EFF;
      display: flex;
      border-radius: 4px 4px 0 0;
      padding-left: 5px;
      cursor: move;
    }

    .drag-content {
      border-radius: 0 0 4px 4px;
      height: 350px;
      display: flex;
      flex-direction: column;
      padding: 5px;

      .content-canvas {
        width: 490px;
        height: 300px;
        display: grid;
        grid-column-gap: 10px;
        grid-row-gap: 10px;
        grid-template-columns: repeat(2, 1fr);
        grid-template-rows: repeat(2, 1fr);

        .item1 {
          grid-area: 1 / 1 / 2 / 2;
        }

        .item2 {
          grid-area: 1 / 2 / 2 / 3;
          --n: 6; /* the number of bar */
          --g: 5px; /* the gap  */
          width: 200px; /* control the size */
          color: #409EFF;
          aspect-ratio: 2;
          border: var(--g) solid;
          padding: var(--g);
          border-radius: 10px;
          background: repeating-linear-gradient(90deg, currentColor 0 calc(100% / var(--n) - var(--g)), #0000 0 calc(100% / var(--n))) 0 0 / calc(100% + var(--g)) content-box;
          position: relative;
          box-sizing: border-box;

          &:before {
            content: "";
            position: absolute;
            inset: 30% -20px 30% 100%;
            background: currentColor;
          }
        }

        .item3 {
          grid-area: 2 / 1 / 3 / 2;
        }

        .item4 {
          grid-area: 2 / 2 / 3 / 3;
        }
      }
    }
  }

  .pag-box {
    width: 400px;
  }
}
</style>
